using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace Shrapnel
{
	public partial class View
    {
        /// <summary>
        /// A set of selected elements
        /// </summary>
        private Selection selection = new Selection();

		/// <summary>
		/// The selection rectangle that is used to select elements on the view.
		/// </summary>
        private SelectionRectangle selectionRectangle = new SelectionRectangle();

        /// <summary>
        /// Selects all the elements on the workview.
        /// </summary>
        public void SelectAll()
        {
            selection.Clear();

            foreach (Layer layer in layers)
                selection.AddRange(layer);

            Invalidate();
        }

        /// <summary>
        /// Deselects all the current selected elements.
        /// </summary>
        public void DeselectAll()
        {
            selection.Clear();
            Invalidate();
        }

        /// <summary>
        /// Delete all currently selected elements and all attached cables
        /// </summary>
        public void DeleteSelection()
        {
            List<Cable> attachedCables = GetCablesAttachedToSelection();

            // Remove selected items from layer
            foreach (Element element in selection)
            {
                if (element.ParentLayer != null)
                {
                    element.ParentLayer.Remove(element);
                    element.ParentLayer = null;
                }
            }

            // Clear up the selection set
            selection.Clear();

            // Remove attached cables from layers
            foreach (Cable cable in attachedCables)
            {
                if (cable.ParentLayer != null)
                {
                    cable.ParentLayer.Remove(cable);
                    cable.ParentLayer = null;
                }
            }

            Invalidate();
        }

		private void OnSelectingStart(Point mousePosition)
		{
			selectionRectangle.StartLocation = viewState.ScreenToWorld(mousePosition);
			selectionRectangle.Location = selectionRectangle.StartLocation;
		}

		private void OnSelectingStop(Point mousePosition)
		{
			BoundingBox selectionBox = selectionRectangle.GetWorldSelectionBox();

			// Enforce minimum selection box size, by growing it in all directions.
			EnforceMinimumBoxSize(ref selectionBox);

			List<Element> selectedItems = GetOverlappingElements(selectionBox, false);

			selection.Clear();

			foreach (Element element in selectedItems)
			{
				selection.Add(element);
			}

			automaticPanner.Stop();

			Invalidate();
		}

		private void OnSelectingTick(Point mousePosition)
		{
			selectionRectangle.Location = viewState.ScreenToWorld(mousePosition);

			UpdateAutomaticPanning(mousePosition);

			Invalidate();
        }
	}
}
